实践 GitHub Actions:template 项目发布静态站
概述
本节将 GitHub Actions 工作流应用到实际的 admin-template 项目中,完成从创建 workflow 文件、配置 GitHub 远程仓库、调整 Vite base 路径到推送触发自动构建部署的完整流程。
实践步骤
Step 1:创建 Workflow 文件
项目根目录/
└── .github/
└── workflows/
└── main.yml ← 创建此文件
text
# .github/workflows/main.yml
name: Deploy to GitHub Pages
on:
push:
branches: [main]
permissions:
contents: read
pages: write
id-token: write
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
with:
version: 8
- uses: actions/setup-node@v4
with:
node-version: 18
cache: 'pnpm'
- run: pnpm install --frozen-lockfile
- run: pnpm build
env:
VITE_BASE_URL: /vue3-admin-template/
- uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./dist
yaml
Step 2:配置 Vite base 路径
// vite.config.ts
export default defineConfig({
// GitHub Pages 的 URL 路径包含仓库名
base: '/vue3-admin-template/',
})
typescript
Step 3:创建 GitHub 仓库
- 登录 GitHub → New Repository
- 填写仓库名称和描述(如
vue3-admin-template) - 选择 Public
- 点击 Create repository
Step 4:提交并推送
# 添加远程仓库
git remote add origin https://github.com/username/vue3-admin-template.git
# 添加 workflow 文件
git add .github/workflows/main.yml
# 提交
git commit -m "feat: add GitHub Actions workflow"
# 推送到 GitHub(触发 Actions)
git push -u origin main
bash
Step 5:验证部署
- 进入 GitHub 仓库 → Actions 标签
- 查看工作流运行状态
- 运行成功后访问
https://username.github.io/vue3-admin-template/
提交信息规范
# 使用 vim 编辑提交信息
git commit
# 按 i 进入编辑模式
# 输入: feat: 添加 GitHub Actions 配置文件
# ESC → :wq 保存退出
# 或使用 -m 参数
git commit -m "feat: 添加 GitHub Actions 配置文件"
bash
GitHub Pages 配置
| 设置项 | 值 |
|---|---|
| Source | Deploy from a branch |
| Branch | gh-pages |
| Custom domain | 可选配置 |
完整文件结构
vue3-admin-template/
├── .github/
│ └── workflows/
│ └── main.yml ← GitHub Actions 配置
├── src/
├── public/
├── vite.config.ts ← base: '/vue3-admin-template/'
├── package.json
└── pnpm-lock.yaml
text
实践要点
- Workflow 文件路径必须为
.github/workflows/*.yml base路径必须与仓库名一致,否则 GitHub Pages 页面空白- 推送到
main分支即触发 Actions 自动构建部署 - 使用
peaceiris/actions-gh-pages自动创建gh-pages分支 - 部署完成后访问地址为
https://<username>.github.io/<repo-name>/
↑